﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace RobotEmulator {
    public partial class RobotEmuForm : Form {
        private SerialPort myConn = new SerialPort();
        int mDc = 1;
        public RobotEmuForm() {
            InitializeComponent();
        }
        private void RobotEmuFormLoad(object sender, EventArgs e) {
        ReTry:
            string[] list = SerialPort.GetPortNames();
            if (list.Length > 0) {
                Array.Sort(list);

                connectionPortComboBox.Items.AddRange(list);
                connectionPortComboBox.SelectedIndex = 0;

                myConn.DataReceived += new SerialDataReceivedEventHandler(MyConnDataReceived);
            }
            else {
                DialogResult DR = MessageBox.Show(@"Your system doesn't have any serial ports!", @"Missing serial port!", MessageBoxButtons.AbortRetryIgnore);
                switch (DR) {
                    case System.Windows.Forms.DialogResult.Abort:
                        Close();
                        break;
                    case System.Windows.Forms.DialogResult.Retry:
                        goto ReTry;
                }
            }
        }
        private void SetSerialPort() {
            myConn.BaudRate = 9600;
            myConn.PortName = Text;
            myConn.DataBits = 8;
            myConn.Parity = Parity.None;
            myConn.StopBits = StopBits.One;
            myConn.ReceivedBytesThreshold = 4;
            //myConn.Encoding = Encoding.GetEncoding("ISO-8859-2");
            //myConn.Encoding = Encoding.;
        }
        private void ConnectButtonClick(object sender, EventArgs e) {
            if (myConn.IsOpen) {
                connectionPortComboBox.Enabled = true;
                myConn.Close();
                connectButton.Text = @"&Open";
                sendTextBox.Enabled = false;
                sendButton.Enabled = false;
            }
            else {
                myConn.PortName = (string)connectionPortComboBox.SelectedItem;
                connectionPortComboBox.Enabled = false;
                connectButton.Text = @"&Close";
                sendTextBox.Enabled = true;
                sendButton.Enabled = false;
                myConn.Open();
                Setup();
            }
            Text = (string)connectionPortComboBox.SelectedItem;
        }

        private void Setup() {
            myConn.DataReceived -= MyConnDataReceived;
            byte input = 0;
            do {
                myConn.Write("    ");
                myConn.Write("MoBRo Project 2011"); UjSor();
                myConn.Write("1) Dc"); UjSor();
                myConn.Write("2) Servo"); UjSor();
                myConn.Write("3) Start"); UjSor();
                myConn.Write("I'm gonna wait for you to decide!"); UjSor();
                myConn.Write("Corrent setting: ");
                if (mDc == 1)
                    myConn.Write("DC");
                else
                    myConn.Write("Servo");
                UjSor();
                for (; ; )
                {
                    if (myConn.BytesToRead > 0) {
                        input = (byte)(myConn.ReadByte() - 48);
                        mDc = (input != 3 ? input : mDc);
                        break;
                    }
                    Thread.Sleep(5);
                }
            } while (input != 3);
            myConn.DataReceived += MyConnDataReceived;
        }

        private void UjSor() {
            myConn.Write("\r\n");
        }

        private void TextBoxKeyPress(object sender, KeyPressEventArgs e) {
            if (e.KeyChar == (char)Keys.Enter)
                myConn.Write(sendTextBox.Text + '\r' + '\n');
        }
        private void MyConnDataReceived(object sender, SerialDataReceivedEventArgs e) {
            this.Invoke(new EventHandler(DoUpdate));
        }
        byte[] StrToByte(string s) {
            byte[] tmp = new byte[s.Length];
            for (int i = 0; i < s.Length; i++)
                tmp[i] = Convert.ToByte(s[i]);
            return tmp;
        }

        bool CheckSum(int[] s) {
            try {
                return (s[0] + s[1] + s[2]) % 53 == s[3];
            }
            catch { return false; }
        }

        int[] mDir;
        private void DoUpdate(object s, EventArgs e) {
            List<int> tmp = new List<int>();
            while (myConn.BytesToRead > 0)
                tmp.Add(myConn.ReadByte());
            mDir = tmp.ToArray();
            if (CheckSum(mDir)) {
                receivedInstructionListBox.Items.Add("B: " + mDir[1] + " J: " + mDir[2]);
                #region old stuff
                //int seb = Convert.ToByte(tmp[1]);
                //switch (tmp[0])
                //{
                //    case 'S': myConn.Write("STOP");
                //        pictureBox.Image = new Bitmap("Pics\\stop.jpg");
                //        break;
                //    case 'W': myConn.Write("ELORE ");
                //        pictureBox.Image = new Bitmap("Pics\\FF.jpg");
                //        break;
                //    case 'E': myConn.Write("E.J. ");
                //        pictureBox.Image = new Bitmap("Pics\\FR.jpg");
                //        break;
                //    case 'D': myConn.Write("JOBBRA ");
                //        pictureBox.Image = new Bitmap("Pics\\TR.jpg");
                //        break;
                //    case 'C': myConn.Write("H.J. ");
                //        pictureBox.Image = new Bitmap("Pics\\BR.jpg");
                //        break;
                //    case 'X': myConn.Write("HATRA ");
                //        pictureBox.Image = new Bitmap("Pics\\BB.jpg");
                //        break;
                //    case 'Y': myConn.Write("H.B. ");
                //        pictureBox.Image = new Bitmap("Pics\\BL.jpg");
                //        break;
                //    case 'A': myConn.Write("BALRA ");
                //        pictureBox.Image = new Bitmap("Pics\\TL.jpg");
                //        break;
                //    case 'Q': myConn.Write("E.B. ");
                //        pictureBox.Image = new Bitmap("Pics\\FL.jpg");
                //        break;
                //}
                //if (seb < 127) myConn.Write("lassan ");
                //else myConn.Write("gyorsan ");
                #endregion
                int LEFT_M = mDir[1], RIGHT_M = mDir[2], eX = 0, eY = 0;
                //deadzone
                if (LEFT_M >= 117 && RIGHT_M >= 117 && LEFT_M <= 137 && RIGHT_M <= 137) {
                    StopMoBRo();
                }
                else {					// még finomhangolni kell!!
                    if (RIGHT_M > 127) {	//Előre
                        if (RIGHT_M > LEFT_M) { //Balra
                            eY = RIGHT_M - 127;
                            eX = (int)(125 / (eY / (LEFT_M - 127.0)) - 125);
                        }
                        else {  //jobbra
                            eY = LEFT_M - 127;
                            eX = (int)(-(125 / (eY / (RIGHT_M - 127.0)) - 125));
                        }
                    }
                    else { 				//Hátrafele
                        if (RIGHT_M < LEFT_M) { //Balra
                            eY = RIGHT_M - 127;
                            eX = (int)(125 / (eY / (LEFT_M - 127.0)) - 125);
                        }
                        else {  //jobbra
                            eY = LEFT_M - 127;
                            eX = (int)(-(125 / (eY / (RIGHT_M - 127.0)) - 125));
                        }
                    }
                    myConn.Write("B: " + mDir[1].ToString() + "  J: " + mDir[2].ToString() + '\r' + '\n');
                    if (eX > -126 && eX < 126 && eY > -126 && eY < 126) {
                        Bitmap A = new Bitmap(260, 260);
                        Graphics g = Graphics.FromImage(A);
                        g.FillRectangle(new SolidBrush(Color.Blue), 120, 120, 20, 20);
                        g.FillPie(new SolidBrush(Color.Red), eX + 125, -eY + 125, 10, 10, 0, 360);
                        pictureBox.Image = A;
                        myConn.Write("B: " + mDir[1].ToString() + "  J: " + mDir[2].ToString() + '\r' + '\n');
                    }
                }
            }
        }


        private void StopMoBRo() {
            myConn.Write("STOP");
            pictureBox.Image = new Bitmap("Pics\\stop.jpg");
        }
        private void SendButtonClick(object sender, EventArgs e) {

        }
    }
}
